package com.swx.generate.util;

import com.aspose.words.*;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataTable;
import com.swx.generate.exception.AppException;

import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;

public class WordUtil {
    private WordUtil() {
    }

    public static Document mergeDocument(Document... srcDocList) {
        try {
            List<Document> docList = new ArrayList<>();
            for (Document nodes : srcDocList) {
                if (nodes != null) {
                    docList.add(nodes);
                }
            }
            if (docList.isEmpty()) {
                throw new AppException("方法调用异常缺少必须的参数");
            }
            Document dstDoc = docList.get(0).deepClone();

            for (int i = 1; i < docList.size(); i++) {
                Document srcDoc = docList.get(i);
                if (srcDoc == null) {
                    continue;
                }
                Body body = dstDoc.getLastSection().getBody();
                for (Section srcSection : srcDoc.getSections()) {
                    NodeCollection<Node> childNodes = srcSection.getBody().getChildNodes();

                    for (Node childNode : childNodes) {
                        Node dstNode = dstDoc.importNode(childNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                        body.appendChild(dstNode);
                    }
                }
            }
            return dstDoc;
        } catch (Exception e) {
            throw new AppException("word合并失败", e);
        }
    }

    public static Document fillWordByMap(Document srcDoc, Map<String, Object> data) throws Exception {

        DocumentBuilder builder = new DocumentBuilder(srcDoc);
        Map<String, String> toData = new HashMap<>();
        for (Map.Entry<String, Object> en : data.entrySet()) {
            String key = en.getKey();
            Object value = en.getValue();

            if (value instanceof List) {
                //写入表数据
                DataTable dataTable = fillListData((List<Map>) value, key, builder);
                srcDoc.getMailMerge().executeWithRegions(dataTable);
            }

            if (value instanceof BufferedImage) {
                builder.moveToMergeField(key);
                builder.insertImage((BufferedImage) value);
            }

            String valueStr = String.valueOf(en.getValue());
            if (value == null || value.equals("null")) {
                continue;
            }

            toData.put(key, valueStr);
        }


        String[] fieldNames = new String[toData.size()];
        Object[] values = new String[toData.size()];

        int i = 0;
        for (Map.Entry<String, String> entry : toData.entrySet()) {
            fieldNames[i] = entry.getKey();
            values[i] = entry.getValue();
            i++;
        }

        //克隆模板
        Document cloneDoc = (Document) srcDoc.deepClone(true);
        cloneDoc.getMailMerge().execute(fieldNames, values);
        return cloneDoc;
    }

    private static DataTable fillListData(List<Map> list, String tableName, DocumentBuilder builder) {
        //创建DataTable,并绑定字段
        DataTable dataTable = new DataTable(tableName);
        for (int i = 0; i < list.size(); i++) {
            DataRow dataRow = dataTable.newRow();
            Map map = list.get(i);
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (!dataTable.getColumns().contains(key)) {
                    dataTable.getColumns().add(key);
                }
                dataRow.set(key, map.get(key));
            }
            dataTable.getRows().add(dataRow);
        }
        return dataTable;
    }


}
